﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Entity;
using DataAccess;

namespace Controller
{
    public class ContractDueController:ControllerBase
    {
        public IList<ContractDueEntity> FindContractDueByLots(int lots)
        {
            var customerPos = (from p in Sdc.CustPOs
                               where p.Status != "completed" && p.Type =="contract"
                               select p);
            IList<ContractDueEntity> contractDueEntities = new List<ContractDueEntity>();
            foreach (var customerPo in customerPos)
            {
                ContractDueEntity contractDueEntity = TransformCustomerPOToContractDueEntity(customerPo);
                if(contractDueEntity.TotalOpenQty<=contractDueEntity.Lot*lots)
                {
                    contractDueEntities.Add(contractDueEntity);
                }
            }
            return contractDueEntities;
        }

        private ContractDueEntity TransformCustomerPOToContractDueEntity(CustPO customerPo)
        {
            ContractDueEntity contractDueEntity = new ContractDueEntity();
            contractDueEntity.ProductId = customerPo.CustPOItems.First().ProductId;
            contractDueEntity.ProductNo = customerPo.CustPOItems.First().Product.No;
            contractDueEntity.CustPoId = customerPo.Id;
            contractDueEntity.CustPoNo = customerPo.No;
            contractDueEntity.Lot = customerPo.CustPOItems.First().Lot;
            contractDueEntity.LatestDeliveryDate = customerPo.CustPOItems.OrderBy(p => p.RequestDate).Last().RequestDate;
            if (customerPo.Type == "purchase" || customerPo.TotalQty == 0)
            {
                contractDueEntity.TotalRequestedQty = customerPo.CustPOItems.Sum(p => p.RequestQty);
            }
            else
            {
                contractDueEntity.TotalRequestedQty = customerPo.TotalQty;
            }

            contractDueEntity.TotalCompletedQty = customerPo.CustPOItems.Sum(p => p.CompleteQty);
            contractDueEntity.TotalOpenQty = contractDueEntity.TotalRequestedQty - contractDueEntity.TotalCompletedQty;

            return contractDueEntity;
        }
    }
}
